package tripx.db.server;

import java.io.IOException;

import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;

import tripx.db.system.Logger;

/**
 * Since we use the xmprpc technique, we must provide a server to handle all the
 * request. We choose the xmlrpc which is implemented by Apache.
 * 
 * @author zhb
 * 
 */
public class DbServer {

	private WebServer server;

	private PropertyHandlerMapping pMapping;

	ServerConfig config;

	/**
	 * Make a new database server, and specify the hander mapping and the server
	 * port.
	 * 
	 * @param pMapping
	 *            the handler mapping
	 * @param port
	 *            the server port
	 */
	public DbServer(PropertyHandlerMapping pMapping, int port) {
		server = new WebServer(port);
		this.pMapping = pMapping;
		config = ServerConfig.getInstance();
		// some initialization
		prepare();
	}

	/**
	 * startup the server
	 */
	public void start() {
		// start the server
		XmlRpcServerConfigImpl config = new XmlRpcServerConfigImpl();
		config.setEnabledForExtensions(true);
		server.getXmlRpcServer().setHandlerMapping(pMapping);
		server.getXmlRpcServer().setConfig(config);
		try {
			server.start();
			Logger.getInstance().info("Database Server Starts");
		} catch (IOException e) {
			Logger.getInstance().err(
					"Binding the database server socket failed.");
		}
	}

	/**
	 * shutdown the server.
	 */
	public void shutdown() {
		server.shutdown();
		Logger.getInstance().info("Database Server Ends");
	}

	private void prepare() {
		// temporary empty
	}
}
